/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: dings
 * Date: 2024-07-08
 * Time: 15:30
 */

class ListNode {
    int val;
    ListNode next;
      ListNode(int x) { val = x; }
  }
class Solution {
    public int kthToLast(ListNode head, int k) {
        //当头指针为空时
        if (head == null) {
            return Integer.MAX_VALUE;
        }

        //当k的值<=0时
        ListNode cur = head;
        int size = 0;
        while (cur != null) {
            size++;
            cur = cur.next;
        }
        if (k <= 0) {
            return Integer.MAX_VALUE;
        }

        //双指针法求解
        ListNode fast = head;
        ListNode slow = head;

        //先让fast指针移动k-1次
        int count = 0;
        while (count != k - 1) {
            fast = fast.next;
            if (fast == null) {//当k值>size时（不合法），fast指针移动的k-1次中，必然会指向null
                return Integer.MAX_VALUE;
            }
            count++;
        }

        //slow和fast同步后移，直至fast指向倒数第一个元素（slow和fast始终保持k-1个移动次数）
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        //返回val
        return slow.val;
    }
}
public class Test {
    public static void main(String[] args) {

    }
}
